package org.jash.shop2111.category

import androidx.paging.PagingSource
import androidx.paging.PagingState
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.net.APIService

class ProductPagingSource(val service:APIService, val cid:Int):PagingSource<Int, Goods>() {
    override fun getRefreshKey(state: PagingState<Int, Goods>): Int? {
        return state.anchorPosition?.let {
            val position = state.closestPageToPosition(it)
            position?.prevKey?.plus(1) ?: position?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Goods> {
        return try {
            val page = params.key ?: 1
            val res = service.getGoods(cid, page, 10)
            LoadResult.Page(
                res.data,
                if (page > 1) page - 1 else null,
                if (res.data.size < 10) null else page + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}